/**
 * Created by 小敏哥 on 2017/8/21.
 */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import style from './index.scss';
import {Toast} from 'antd-mobile';
import AlipayJSOperation from '../../utils/alipayJSOperation';
import PageBar from '../../components/common/pageBar';
import BackMeanSure from '../../utils/backMeanSure';
import ReModal from '../../components/common/reModal';
import SendCxytjMessage from '../../utils/sendCxytjMessage';

import {
    uploadImage,
    testImage,
    insuranceImage,
    idCardObverseImage,
    idCardBackImage,
    taxImage,
    licenseObverseImage,
    licenseBackImage,
    userAndCardImage,
    certificateImage
} from '../../actions/uploadPageAction';
import UploadImg from '../../components/uploadPage/uploadImg';
import {setRequirementStatus} from '../../actions/taxConfirmAction'

class UploadPage extends Component {
    constructor(props) {
        super(props);
        this.fileChange = this.fileChange.bind(this);
        /**
         * width:图片宽度
         * height:图片高度
         * title：页面标题
         * littleTitle：小标题
         * backgroundImage：上传控件背景
         * imgSourcesOperation：上传结束后回传数据的操作
         * imgSourcesName：上传结束后回传数据存储位置
         * exampleImg:实例图片
         * bottomMessage：底部相关提醒文字
         **/
        this.source = {
            JQX: {
                messages: {
                    title: '交强险审核',
                    littleTitle: "请上传交强险保单照片",
                    tipsImg: "./images/uploadPage/pic_insurance.png",
                    exampleImg:'./images/uploadPage/insuranceExample.png',
                    bottomMessage:['1.交强险保单为购买保险后，保险公司提供的凭证；','2.请确保交强险保单截止有效期在当前办理时间之后；','3.请确保交强险边框完整，字体清晰，保单信息清晰可见。'],
                },
                content: [{
                    width: "100%",
                    height: "5.84rem",
                    backgroundImage: "./images/uploadPage/insurance.png",
                    imgSourcesOperation: insuranceImage,
                    imgSourcesName: 'insuranceImg',
                }]
            },
            CLDJZ: {
                messages: {
                    title: '车辆登记证审核',
                    littleTitle: "请上传车辆登记证照片",
                    tipsImg: "./images/uploadPage/pic_insurance.png",
                    exampleImg:'./images/uploadPage/certificateExample.png',
                    bottomMessage:['1. 请确保车辆登记证边框完整，字体清晰，车辆登记证信息清晰可见。'],
                },
                content: [{
                    width: "100%",
                    height: "5.84rem",
                    backgroundImage: "./images/uploadPage/certificate.png",
                    imgSourcesOperation: certificateImage,
                    imgSourcesName: 'certificateImage',
                }]
            }
            ,
            CCS: {
                messages: {
                    title: '车船税审核',
                    littleTitle: "请上传车船税照片",
                    tipsImg: "./images/uploadPage/pic_insurance.png",
                    exampleImg:'./images/uploadPage/taxExample.png',
                    bottomMessage:['1. 若在办理交强险时，已一并办理车船税，则请直接上传交强险保单照片。','2. 请确定车船税边框完整，字体清晰，车船税信息清晰可见'],
                },
                content: [{
                    width: "100%",
                    height: "5.84rem",
                    backgroundImage: "./images/uploadPage/tax.png",
                    imgSourcesOperation: taxImage,
                    imgSourcesName: 'taxImg',
                }]
            }
            ,
            XSZ: {
                messages: {
                    title: '行驶证正副本审核',
                    littleTitle: "请上传行驶证正副本照片",
                    tipsImg: "./images/uploadPage/pic_license.png",
                    exampleImg:'./images/uploadPage/licenseExample.png',
                    bottomMessage:['1. 请确保行驶证边框完整，字体清晰，行驶证信息清晰可见'],
                },
                content: [{
                    width: "100%",
                    height: "4rem",
                    backgroundImage: "./images/uploadPage/license1.png",
                    imgSourcesOperation: licenseObverseImage,
                    imgSourcesName: 'licenseObverseImg',
                },
                    {
                        width: "100%",
                        height: "4rem",
                        backgroundImage: "./images/uploadPage/license2.png",
                        imgSourcesOperation: licenseBackImage,
                        imgSourcesName: 'licenseBackImg',
                    }
                ]
            }
            ,
            SFZ: {
                messages: {
                    title: '身份证正反面审核',
                    littleTitle: "请上传身份证正反面照片",
                    tipsImg: "./images/uploadPage/pic_idcard.png",
                    exampleImg:'./images/uploadPage/idCardExample.png',
                    bottomMessage:['1. 身份证为大陆公民持有的本人二代身份证；','2. 请确保身份证边框完整，字体清晰，证件号码清晰可见。'],
                },
                content: [{
                    width: "100%",
                    height: "4rem",
                    backgroundImage: "./images/uploadPage/idCard1.png",
                    imgSourcesOperation: idCardObverseImage,
                    imgSourcesName: 'idCardObverseImg',
                },
                    {
                        width: "100%",
                        height: "4rem",
                        backgroundImage: "./images/uploadPage/idCard2.png",
                        imgSourcesOperation: idCardBackImage,
                        imgSourcesName: 'idCardBackImg',
                    }
                ]
            }
            ,
            SCSFZ: {
                messages: {
                    title: '车主手持身份证照片审核',
                    littleTitle: "请上传车主手持身份证照片",
                    tipsImg: "./images/uploadPage/pic_userAndCard.png",
                    exampleImg:'./images/uploadPage/userAndCardExample.png',
                    bottomMessage:['1. 请勿让证件照遮挡住面部；','2. 请确保照片中您本人以及身份证上的信息清晰可见。'],
                },
                content: [{
                    width: "100%",
                    height: "5.84rem",
                    backgroundImage: "./images/uploadPage/userAndCard.png",
                    imgSourcesOperation: userAndCardImage,
                    imgSourcesName: 'userAndCardImg',
                }]
            }
        };
        this.state = {
            messages: this.source[props.params.taxId].messages,
            content: this.source[props.params.taxId].content
        };
        this.backMeanSureInstance = new BackMeanSure(this.backMeanSure.bind(this), 'uploadPage');
    }

    backMeanSure(back, stay, toUrl) {
        let isDirty = false;
        for (var i = 0; i < this.state.content.length; i++) {
            if (this.props[this.state.content[i].imgSourcesName] && this.props[this.state.content[i].imgSourcesName].url) {
                isDirty = true;
                break;
            }
        }
        if (!isDirty) {
            back();
        }
        else {
            ReModal.confirm('是否放弃提交资料审核？', () => {
                back();
            }, () => {
                stay();
            })
        }
    }

    //清除所有图片数据缓存，包括上传状态和url
    deleteAllImgSource() {
        for (var i = 0; i < this.state.content.length; i++) {
            this.deleteImg(this.state.content[i].imgSourcesOperation);
        }
    }


    //将图片数据上传到服务器
    //data:图片数据
    //imgSourcesOperation处理图片数据返回的数据的操作
    fileChange(data, imgSourcesOperation) {
        if (data == '') {
            //无图片数据时仅删除全局数据源
            this.deleteImg(imgSourcesOperation);
        }
        else {
            this.props.dispatch(uploadImage(data, imgSourcesOperation,()=>{
                this.deleteImg(imgSourcesOperation);
            }));
        }
    }

    //后退时关闭loading
    componentWillUnmount(){
        Toast.hide();
    }

    componentDidMount() {
        AlipayJSOperation.setRightButtonStatus(false);
        AlipayJSOperation.setTitle(this.state.messages.title);
        document.querySelector("title").innerHTML = this.state.messages.title;
        this.backMeanSureInstance.bindBackMeansure();
        //清除
        this.deleteAllImgSource()
    }

    //提交前对未上传进行拦截
    beforeSubmit() {
        let canSubmit = true;
        for (var i = 0; i < this.state.content.length; i++) {
            if (!(this.props[this.state.content[i].imgSourcesName] && this.props[this.state.content[i].imgSourcesName].url)) {
                canSubmit = false;
                break;
            }
        }
        return canSubmit;
    }

    submitImages() {
        if (this.beforeSubmit()) {
            this.props.dispatch(setRequirementStatus({
                id: this.props.params.documentId,
                status: 2,
                imgUrl: this.props[this.state.content[0].imgSourcesName].url,
                imgSecUrl: this.state.content.length > 1 ? this.props[this.state.content[1].imgSourcesName].url : '',
            }, () => {
                //根据路由传入的backSteps确定回退步数（+2的原因：本页面做了拦截后退的操作，在此页面的栈顶追加了两条空的浏览记录，估此处为了正确返回，需要加上2）
                let backSteps = (this.props.params.backSteps ? parseInt(this.props.params.backSteps) : 1) + 2;
                history.go(-1 * backSteps);
            }));
        }
        else {
            Toast.info('请上传完整资料', 2);
        }
        SendCxytjMessage.sendMessage({
            eventId: 'H5_E_IInterspectionee_ClickSubmit',
            attr1: this.props.params.taxId //属性1
        });
    }

    //删除图片回调，清除数据源缓存
    deleteImg(imgSourcesOperation) {
        this.props.dispatch(imgSourcesOperation({
            url: "",
            loaded: false
        }))
    }

    //构建底部提示文字
    structBottomMessage(){
        return this.state.messages.bottomMessage.map((item,index)=>{
            return <p key={index}>{item}</p>
        });
    }

    uploadClickCallBack() {
        SendCxytjMessage.sendMessage({
            eventId: 'H5_E_Interspection_ClickPicture',
            attr1: this.props.params.taxId //属性1
        });
    }

    deleteClickCallBack() {
        SendCxytjMessage.sendMessage({
            eventId: 'H5_E_Interspectione_ClickDeletePicture',
            attr1: this.props.params.taxId //属性1
        });
    }

    deleteOkCallBack() {
        SendCxytjMessage.sendMessage({
            eventId: 'H5_E_Interspectione_ClickComfirmDelete',
            attr1: this.props.params.taxId //属性1
        });
    }

    deleteCancelCallBack() {
        SendCxytjMessage.sendMessage({
            eventId: 'H5_E_Interspectione_ClickCancerDelete',
            attr1: this.props.params.taxId //属性1
        });
    }

    render() {
        return <div className={style.container}>
            <PageBar title={this.state.messages.title}/>
            <div className={style.title}><div>{this.state.messages.littleTitle}</div><div onClick={()=>{ReModal.showOnlyComponent(<img className={style.imgDialog} src={this.state.messages.exampleImg}/>)}}><img src="./images/uploadPage/tipsIcon.png"/><span>表单样例</span></div></div>
            <div className={style.uploadContainer}>
                {
                    this.state.content.map((item, index) => {
                        return <UploadImg key={index}
                                          fileChange={(data) => {
                                              this.fileChange(data, item.imgSourcesOperation)
                                          }}
                                          uploaded={this.props[item.imgSourcesName] ? this.props[item.imgSourcesName].loaded : false}
                                          width={item.width}
                                          height={item.height}
                                          backgroundImage={item.backgroundImage}
                                          uploadClickCallBack={this.uploadClickCallBack.bind(this)}
                                          deleteClickCallBack={this.deleteClickCallBack.bind(this)}
                                          deleteOkCallBack={this.deleteOkCallBack.bind(this)}
                                          deleteCancelCallBack={this.deleteCancelCallBack.bind(this)}/>
                    })
                }
            </div>
            <div className={style.uploadMessageContainer}>
                <div>
                    <div>提交后将在1个工作日内</div>
                    <div>通过客服、消息提醒通知您审核结果，请留意。</div>
                </div>
            </div>
            <div className={style.tipsMessage}>证件拍摄要求</div>
            <div className={style.tipsImg}>
                <img src={this.state.messages.tipsImg}/>
            </div>
            <div className={style.bottomMessage}>
                {
                    this.structBottomMessage()
                }
            </div>
            <div className={style.blank}></div>
            <div className={style.buttonContainer}>
                <button className={style.submit} onClick={this.submitImages.bind(this)}>提交审核</button>
            </div>
        </div>
    }
}


function mapStateToProps(state) {
    return Object.assign({}, state.uploadPage);
}

export default connect(mapStateToProps)(UploadPage)